package com.zb.controller;

import java.io.File;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.zb.Service.FiletableService;
import com.zb.Service.FiletypeService;
import com.zb.entity.Filetable;
import com.zb.entity.Filetype;
import com.zb.entity.Tree;
import com.zb.entity.User;
import com.zb.util.CCRDFile;

@Scope("prototype")
@Component
@RequestMapping("/file")
public class FileManageController implements ServletContextAware{

	private ServletContext servletContext;
	@Autowired
	private FiletableService fts;
	
	public void setServletContext(ServletContext context) {
		this.servletContext  = context;
	}

	@ResponseBody
	@RequestMapping(params = "op=showroot")
	public List<Tree> showRoot(HttpSession session){
		User user= (User)session.getAttribute("sys_user");
		List<Tree> tlist = fts.showRootFile(user.getDepartment().getId());
		return tlist;
	}
	
	@ResponseBody
	@RequestMapping(params = "op=showflist")
	//通过点击时的文件id得到该文件下的文件列表 当pid为null时出出查询user所在部门的列表
	public List<Filetable> getFileList(HttpSession session,Integer pid){
		User user= (User)session.getAttribute("sys_user");
		int npid = 0;
		if(pid==null){
			npid=1;
		}else{
			npid=pid;
		}
		List<Filetable> flist = fts.getListById(npid, user.getId());
		return flist;
	}
	@ResponseBody
	@RequestMapping(params = "op=showchild")
	public List<Filetable> getFileChild(int pid,int typeid){
		List<Filetable> flist = null;
		if(typeid==-1){
			flist = fts.getListByPid(pid);
		}
		return flist;
	}
	@RequestMapping(params = "op=doupdate")
	public String updateFile(Filetable file){
		//修改文件夹名时需要处理数据库中文件的路径以及其子文件的路径
		if(file.getFiletype().getId()==-1){
			String oldpath = file.getPath();
			int index = oldpath.substring(0, oldpath.length()-1).lastIndexOf("/");
			String newpath = oldpath.substring(0, index+1)+file.getName()+"/";
			file.setPath(newpath);
			fts.updateFileInfo(file);
			List<Filetable> flist = fts.getChildByPath(oldpath+"%");
			for (Filetable f : flist) {
				String oldcpath = f.getPath();
				String newcpath = newpath+oldcpath.substring(oldpath.length());
				f.setPath(newcpath);
				fts.updateFileInfo(f);
			}
			//修改文件夹名
			String realpath = this.servletContext.getRealPath("/文档管理"+oldpath);
			File phyfile = new File(realpath);
			File newphyfile = new File(this.servletContext.getRealPath("/文档管理"+newpath));
 			phyfile.renameTo(newphyfile);
		}else{
			Filetable f = fts.getFileById(file.getId());
			String realpath = this.servletContext.getRealPath("/文档管理"+file.getPath());
			File phyfile = new File(realpath+"/"+f.getName()+"."+f.getFiletype().getName());
			phyfile.renameTo(new File(realpath+"/"+file.getName()+"."+f.getFiletype().getName()));
			fts.updateFileInfo(file);
		}
		return "fileshow";
	}
	@ResponseBody
	@RequestMapping(params = "op=givemepath")
	public String getPath(Integer pid){
		if(pid==null){
			pid=1;
		}
		Filetable file = fts.getFileById(pid);
		return file.getPath();
		
	}
	@RequestMapping(params = "op=addfloder")
	public String addFolder(HttpSession session,String dname,String nowpath,String dtip,Integer dpid){
		Filetable f = fts.getFileById(dpid);
		User u = (User)session.getAttribute("sys_user");
		Filetable ft = new Filetable();
		ft.setName(dname);
		ft.setSecid(dpid);
		ft.setDepartment(f.getDepartment(	));
		ft.setFiletype(new Filetype(-1));
		ft.setUser(u);
		ft.setPath(nowpath+dname+"/");
		ft.setTip(dtip);
		String realpath = this.servletContext.getRealPath("/文档管理"+ft.getPath());
		if(CCRDFile.createDir(realpath)){
			fts.addFile(ft);
		}else{

		}
		return "fileshow";
	}
	@RequestMapping(params = "op=addfile")
	public String addFile(@RequestParam("file")CommonsMultipartFile file,
			String fname,String nowpath,Integer dpid,int filetype,String ftip,HttpSession session,ModelMap modelmap){
		if (!file.isEmpty()) {
			   String path = this.servletContext.getRealPath("/文档管理"+nowpath);  //获取本地存储路径
			   System.out.println(path);
			   String fileName = file.getOriginalFilename();
			   String fileType = fileName.substring(fileName.lastIndexOf("."));
			   System.out.println(fileType);
			   String typename = fs.getNameById(filetype);
			   if(fileType.equals('.'+typename)){
				   File file2 = new File(path,fname + fileType); //新建一个文件
				   if(!CCRDFile.judeFileExists(file2)){
					   try {
						    file.getFileItem().write(file2); //将上传的文件写入新建的文件中
					   } catch (Exception e) {
						    e.printStackTrace();
					   }
					   if(true){
						   Filetable f = fts.getFileById(dpid);
							User u = (User)session.getAttribute("sys_user");
							Filetable ft = new Filetable();
							ft.setName(fname);
							ft.setSecid(dpid);
							ft.setDepartment(f.getDepartment());
							ft.setFiletype(new Filetype(filetype));
							ft.setUser(u);
							ft.setPath(nowpath);
							ft.setTip(ftip);
							fts.addFile(ft);
							modelmap.put("msg", "上传成功");
					   }
				   }else{
					   modelmap.put("msg", "上传失败：文件已存在");
					   System.out.println("文件已存在");
				   }
			   }else{
				   modelmap.put("msg", "上传失败：上传类型不匹配");
				   System.out.println("上传类型不匹配");
			   }
			}else{
				 modelmap.put("msg", "上传失败：没有上传文件");
				 System.out.println("没有上传文件");
			}
		return "fileshow";
	}
	@Autowired
	private FiletypeService fs;
	@ResponseBody
	@RequestMapping(params = "op=gettype")
	public List<Filetype> gettype(){
		List<Filetype> tlist = fs.getTypeList();
		return tlist;
	}
	@RequestMapping(params = "op=changedelete")
	public String changeDelete(Integer id,Integer deletestate,ModelMap modelmap){
		Filetable ft = new Filetable();
		ft.setId(id);
		ft.setDeletestate(deletestate);
		int result = fts.updateFileState(ft);
		if(result>0){
			modelmap.put("msg", "操作成功！");
		}else{
			modelmap.put("msg", "操作失败！");
		}
		return "fileshow";
	}
	@RequestMapping(params = "op=changedelete2")
	public String changeDelete2(Integer id,Integer deletestate,ModelMap modelmap){
		Filetable ft = new Filetable();
		ft.setId(id);
		ft.setDeletestate(deletestate);
		int result = fts.updateFileState(ft);
		if(result>0){
			modelmap.put("msg", "操作成功！");
		}else{
			modelmap.put("msg", "操作失败！");
		}
		return "recyclefile";
	}
	@ResponseBody
	@RequestMapping(params = "op=showdeleteflist")
	public List<Filetable> showDeleteFlist(HttpSession session){
		User user = (User)session.getAttribute("sys_user");
		List<Filetable> flist = fts.getDeleteFileList(user.getId());
		return flist;
	}
	@RequestMapping(params = "op=deletefile")
	public String deleteFile(int id,String path,int typeid,ModelMap modelmap){
		CCRDFile ccr = new CCRDFile();
		if(typeid!=-1){
			Filetable ft = fts.getFileById(id);
			String realpath = this.servletContext.getRealPath("/文档管理"+ft.getPath());
			File phyfile = new File(realpath+"/"+ft.getName()+"."+ft.getFiletype().getName());
			ccr.deleteFile(phyfile.getPath());
			fts.delectFileById(id);
		}else{
			String realpath = this.servletContext.getRealPath("/文档管理"+path);
			ccr.deleteDirectory(realpath);
			fts.delectFlistByPath(path);
		}
		modelmap.put("msg", "删除成功");
		return "recyclefile";
	}
	@RequestMapping(params = "op=updatetype")
	public String updateFileType(String doc,String docx,String xls,String xlsx,
			String ppt,String rar,String txt,ModelMap modelmap){
		if(doc==null){
			fs.updateType("doc", 0);
		}else{
			fs.updateType("doc", 1);
		}
		
		if(docx==null){
			fs.updateType("docx", 0);
		}else{
			fs.updateType("docx", 1);
		}
		
		if(xls==null){
			fs.updateType("xls", 0);
		}else{
			fs.updateType("xls", 1);
		}
		
		if(xlsx==null){
			fs.updateType("xlsx", 0);
		}else{
			fs.updateType("xlsx", 1);
		}
		
		if(ppt==null){
			fs.updateType("ppt", 0);
		}else{
			fs.updateType("ppt", 1);
		}
		
		if(rar==null){
			fs.updateType("rar", 0);
		}else{
			fs.updateType("rar", 1);
		}
		
		if(txt==null){
			fs.updateType("txt", 0);
		}else{
			fs.updateType("txt", 1);
		}
		return "redirect:file.html?op=showupdatetype&talk=1";
	}
	@RequestMapping(params = "op=showupdatetype")
	public String getAllTypeList(Integer talk,ModelMap modelmap){
		if(talk!=null){
			modelmap.put("msg", "保存成功");
		}
		List<Filetype> flist = fs.getAllTypeList();
		modelmap.put("list", flist);
		return "uploadoption";
	}
}
